<template>
  <page-header-wrapper :title="false">
    <a-card title="修改密码">
      <a-row>
        <a-col :span="5">
          <a-form-model ref="ruleForm" layout="vertical" :rules="rules" :model="form">
            <a-form-model-item label="原密码" prop="old_password">
              <a-input-password v-model="form.old_password" type="text"></a-input-password>
            </a-form-model-item>
            <a-form-model-item label="新密码" prop="new_password">
              <a-input-password v-model="form.new_password" type="text"></a-input-password>
            </a-form-model-item>
            <a-form-model-item label="确认新密码" prop="retype_password">
              <a-input-password v-model="form.retype_password" type="text"></a-input-password>
            </a-form-model-item>
            <a-form-model-item>
              <a-button type="primary" @click="onSubmit">提交修改</a-button>
            </a-form-model-item>
          </a-form-model>
        </a-col>
      </a-row>
    </a-card>
  </page-header-wrapper>
</template>

<script>
  import { getPassword, changePassword } from '@/api/common'

  export default {
    name: 'ChangePassword',
    data () {
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入新密码'))
        } else {
          if (this.form.retype_password !== '') {
            this.$refs.ruleForm.validateField('checkPass')
          }
          callback()
        }
      }
      const validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再一次输入新密码'))
        } else if (value !== this.form.new_password) {
          callback(new Error('两次输入的密码必须一致'))
        } else {
          callback()
        }
      }
      return {
        form: {
          old_password: '',
          new_password: '',
          retype_password: ''
        },
        rules: {
          old_password: [
            { required: true, message: '请输入原密码', trigger: 'blur' }
          ],
          new_password: [
            { validator: validatePass, trigger: 'change' }
          ],
          retype_password: [
            { validator: validatePass2, trigger: 'change' }
          ]
        }
      }
    },
    created () {
      getPassword()
    },
    methods: {
      onSubmit () {
        const app = this
        app.$refs.ruleForm.validate(valid => {
          if (valid) {
            const form = {}
            for (const k in app.form) {
              form['change_password[' + k + ']'] = app.form[k]
            }
            changePassword(form).then(res => {
              if (res.status === 0) {
                app.$info({
                  title: '修改密码成功'
                })
                app.form = {}
              } else {
                app.$warning({
                  title: res.msg
                })
              }
            })
          } else {
            return false
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
